package learn_concurrent._3;

import java.util.Random;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class T2 {
	static final Logger logger = LoggerFactory.getLogger(T2.class);

	static Random random = new Random();

	public static void main(String[] args) throws InterruptedException {
		Account a = new Account(1000);
		Account b = new Account(1000);
		
		Thread t1 = new Thread(() -> transfer1000(a, b));
		Thread t2 = new Thread(() -> transfer1000(b, a));
		
		t1.start();
		t2.start();
		t1.join();
		t2.join();
		
		logger.info("Total : {}", a.getMoney() + b.getMoney());
		
	}

	private static void transfer1000(Account from, Account to) {
		for(int i = 0; i < 1000; i++) {
			from.transfer(to, randomAmount());
		}
	}

	// 1 ~ 100
	private static int randomAmount() {
		return random.nextInt(100) + 1;
	}
}

class Account {

	private int money;

	public Account(int money) {
		this.money = money;
	}

	public int getMoney() {
		return money;
	}

	public void setMoney(int money) {
		this.money = money;
	}

	public void transfer(Account target, int amount) {
		synchronized(Account.class) {
			if (money >= amount) {
				setMoney(money - amount);
				target.setMoney(target.getMoney() + amount);
			}
		}
	}

}
